<template>
    <div class="user-detail-container">
      <div class="page-header">
        <div class="header-left">
          <span class="detail-title">用户详情: {{ userData.username }}</span>
        </div>
        <el-button @click="goBack" class="return-btn">返回</el-button>
      </div>
      
      <div class="detail-content">
        <!-- 基本信息 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          
          <div class="user-info">
            <div class="basic-info">
              <el-avatar :size="80" :src="getAvatarUrl(userData.avatar)">
                {{ userData.username.charAt(0).toUpperCase() }}
              </el-avatar>
              
              <div class="user-meta">
                <h2>{{ userData.username }}</h2>
              </div>
            </div>
            
            <el-descriptions :column="2" border>
              <el-descriptions-item label="用户ID">{{ userData.id }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ userData.email }}</el-descriptions-item>
              <el-descriptions-item label="手机号码">{{ userData.phone || '未设置' }}</el-descriptions-item>
              <el-descriptions-item label="注册时间">{{ userData.registerTime }}</el-descriptions-item>
              <el-descriptions-item label="最后登录时间">{{ userData.lastLoginTime || '未记录' }}</el-descriptions-item>
              <el-descriptions-item label="累计消费">¥{{ (parseFloat(userData.totalSpent) || 0).toFixed(2) }}</el-descriptions-item>
              <el-descriptions-item label="订单数量">{{ userData.orderCount }}</el-descriptions-item>
              <el-descriptions-item label="收货地址数">{{ userData.addressCount }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
        
        <!-- 订单历史 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>订单历史</span>
              <el-button size="small" @click="viewAllOrders">查看全部订单</el-button>
            </div>
          </template>
          
          <el-table
            :data="userData.recentOrders"
            border
            style="width: 100%"
            v-loading="ordersLoading"
          >
            <el-table-column prop="id" label="订单号" width="180" />
            
            <el-table-column prop="amount" label="订单金额" width="120">
              <template #default="scope">
                ¥{{ (parseFloat(scope.row.amount) || 0).toFixed(2) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="订单状态" width="120">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(getStatusText(scope.row.status))">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="createTime" label="下单时间" width="180" />
            
            <el-table-column label="商品信息" min-width="200">
              <template #default="scope">
                <div v-for="(item, index) in scope.row.items" :key="index" class="order-item">
                  {{ item.name }} x {{ item.quantity }}
                </div>
              </template>
            </el-table-column>
            
            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="viewOrderDetail(scope.row)">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-empty v-if="userData.recentOrders?.length === 0" description="暂无订单记录" />
        </el-card>
        
        <!-- 收货地址 -->
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>收货地址</span>
            </div>
          </template>
          
          <el-table
            :data="userData.addresses"
            border
            style="width: 100%"
            v-loading="addressesLoading"
          >
            <el-table-column prop="name" label="收货人" width="120" />
            
            <el-table-column prop="phone" label="联系电话" width="140" />
            
            <el-table-column prop="address" label="详细地址" min-width="250" show-overflow-tooltip />
            
            <el-table-column prop="postalCode" label="邮政编码" width="120" />
            
            <el-table-column prop="isDefault" label="是否默认" width="100" v-if="false">
              <template #default="scope">
                <el-tag v-if="scope.row.isDefault" type="success">默认</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
          
          <el-empty v-if="userData.addresses?.length === 0" description="暂无收货地址" />
        </el-card>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getUserDetail, getUserOrders } from '../../api/user'
  
  const route = useRoute()
  const router = useRouter()
  const ordersLoading = ref(false)
  const addressesLoading = ref(false)
  const loading = ref(false)
  
  // 订单状态对应的标签类型
  const getOrderStatusType = (status) => {
    const typeMap = {
      '待付款': 'warning',
      '待发货': 'info',
      '已发货': 'primary',
      '已完成': 'success',
      '已取消': 'danger',
      '已退款': 'danger'
    }
    return typeMap[status] || 'info'
  }
  
  // 获取状态文本
  const getStatusText = (status) => {
    const map = {
      // 中文状态映射（保持不变）
      '待付款': '待付款',
      '待发货': '待发货',
      '已发货': '已发货',
      '已完成': '已完成',
      '已取消': '已取消',
      '已退款': '已退款',
      // 英文状态映射
      'pending': '待付款',
      'paid': '待发货',
      'shipped': '已发货',
      'completed': '已完成',
      'cancelled': '已取消',
      'refunded': '已退款'
    }
    return map[status] || status
  }
  
  // 用户数据
  const userData = reactive({
    id: '',
    username: '',
    avatar: '',
    email: '',
    phone: '',
    registerTime: '',
    lastLoginTime: '',
    totalSpent: 0,
    orderCount: 0,
    addressCount: 0,
    recentOrders: [],
    addresses: []
  })
  
  // 获取用户详情
  const fetchUserDetail = async (id) => {
    loading.value = true
    try {
      const data = await getUserDetail(id)
      
      // 确保数值类型字段正确
      data.totalSpent = parseFloat(data.totalSpent || 0)
      data.orderCount = parseInt(data.orderCount || 0)
      data.addressCount = parseInt(data.addressCount || 0)
      
      // 处理订单列表中的金额
      if (data.recentOrders && data.recentOrders.length > 0) {
        data.recentOrders = data.recentOrders.map(order => ({
          ...order,
          amount: parseFloat(order.amount || 0)
        }))
      }
      
      Object.assign(userData, data)
    } catch (error) {
      ElMessage.error('获取用户信息失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }
  
  // 获取用户订单
  const fetchUserOrders = async (id) => {
    ordersLoading.value = true
    
    // 实际项目中应该通过API获取数据
    // try {
    //   const { data } = await getUserOrders(id, { page: 1, limit: 5 })
    //   userData.recentOrders = data.items
    // } catch (error) {
    //   ElMessage.error('获取订单列表失败: ' + error.message)
    // }
    
    // 模拟
    setTimeout(() => {
      ordersLoading.value = false
    }, 500)
  }
  
  // 获取用户地址
  const fetchUserAddresses = async (id) => {
    addressesLoading.value = true
    
    // 实际项目中应该通过API获取数据
    // try {
    //   const { data } = await getUserAddresses(id)
    //   userData.addresses = data
    // } catch (error) {
    //   ElMessage.error('获取地址列表失败: ' + error.message)
    // }
    
    // 模拟
    setTimeout(() => {
      addressesLoading.value = false
    }, 500)
  }
  
  // 返回上一页
  const goBack = () => {
    router.back()
  }
  
  // 查看所有订单
  const viewAllOrders = () => {
    router.push({
      path: '/orders',
      query: { userId: userData.id }
    })
  }
  
  // 查看订单详情
  const viewOrderDetail = (row) => {
    router.push(`/orders/${row.id}`)
  }
  
  // 添加处理头像URL的函数
  const getAvatarUrl = (avatar) => {
    if (!avatar) return '';
    
    // 检查是否已经是完整的URL
    if (avatar.startsWith('http')) return avatar;
    
    // 服务器基础URL
    const serverBaseUrl = 'http://localhost:5000';
    
    // 确保路径正确
    const path = avatar.startsWith('/') ? avatar : `/${avatar}`;
    
    // 如果是相对路径，添加uploads前缀
    if (!path.startsWith('/uploads') && !path.startsWith('/api')) {
      return `${serverBaseUrl}/uploads${path}`;
    }
    
    return `${serverBaseUrl}${path}`;
  }
  
  onMounted(() => {
    const userId = route.params.id
    fetchUserDetail(userId)
    fetchUserOrders(userId)
    fetchUserAddresses(userId)
  })
  </script>
  
  <style scoped>
  .user-detail-container {
    padding: 20px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 60px);
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header-left {
    display: flex;
    align-items: center;
  }
  
  .detail-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
  }
  
  .return-btn {
    margin-left: auto;
  }
  
  .detail-content {
    margin-top: 20px;
  }
  
  .mb-20 {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .box-card {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .user-info {
    padding: 15px;
  }
  
  .basic-info {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px 20px;
    border-bottom: 1px dashed #ebeef5;
  }
  
  .user-meta {
    margin-left: 20px;
  }
  
  .user-meta h2 {
    margin: 0;
    font-size: 18px;
    line-height: 1.5;
  }
  
  .user-status {
    margin-top: 5px;
  }
  
  .order-item {
    margin-bottom: 5px;
    line-height: 1.4;
  }
  </style>